import Const from "./const"
import Vue from "vue"
import VueResource from "vue-resource"
import Core from "../core"
import router from '../../src/router/index';

function Api() {
  Vue.use(VueResource);

  let apiList = {
    Article: {
      getArticleList: ['GET|article/list', 'type', 'page', 'limit'],
      getArticleDetail: ['GET|article/detail', 'id']
    }
  };

  let api = {};
  for (let moduleKey in apiList) {
    let moduleApiList = apiList[moduleKey];
    api[moduleKey] = {};
    for (let functionName in moduleApiList) {
      let config = moduleApiList[functionName];
      api[moduleKey][functionName] = (function (config) {
        return function () {
          let req = config[0].split("|");
          let method = req[0];
          let action = req[1];
          let data = {};
          if (config.length > 1) {
            for (let i = 1; i < config.length; i++) {
              let key = config[i];
              let value = arguments[i - 1];
              if (value === undefined) {
                continue;
              }
              data[key] = value;
            }
          }
          return request(method, action, data);
        };
      })(config);
    }
  }

  api.getUrl = getUrl;

  return api;

  function getUrl(api, data) {
    let token = Core.Data.getToken() || "";
    let url = `${Const.NET.END_POINT}/${api}`;
    let params = {
      token: token
    };

    data = Object.assign(params, data);
    url = url + '?' + transformObjectToUrlencodedData(data);
    return url;
  }

  function request(method, api, data) {
    let token = Core.Data.getToken() || '';
    let url = `${Const.NET.END_POINT}/${api}`;
    let body = '';

    let params = {
      token: token
    };

    body = Object.assign(params, data);
    console.log(url + "?" + transformObjectToUrlencodedData(body));

    let headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    return new Promise(function (resolve, reject) {
      let req = "";
      if (method == "GET") {
        req = Vue.http.get(url + "?" + transformObjectToUrlencodedData(body))
      } else {
        req = Vue.http.post(url, transformObjectToUrlencodedData(body), {headers: headers})
      }
      req.then(
        function (response) {
          let body = response.body;
          if (response.data.hasOwnProperty('code') && response.data.code === Const.ERROR.ERROR_TOKEN_INVALID) {
            Core.Data.clearAuthData();
            router.push({path: '/login'});
            return;
          }
          if (body.hasOwnProperty('code') && body.code === 0) {
            if (body.hasOwnProperty('error')) {
              console.error(body.error);
              handleError(body.error);
              return reject(body.error);
            } else {
              return resolve(body.data)
            }
          }

          handleError(body.message);
          return reject(body);
        },
        function (error) {
          handleError(error.message);
          reject(error);
        }
      );
    })
  }

  function handleError(message) {
    alert(message);
  }

  function transformObjectToUrlencodedData(obj) {
    let p = [];
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
      }
    }
    return p.join('&');
  }
}

export default new Api();
